package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.XiaoLongQianBaoUtil;
import com.block.db.entity.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 小龙钱包
 */
@Service
public class XiaoLongQianBaoApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", memberSourceInfo.getMobileMd5());
        paramMap.put("sex", memberSourceInfo.getSex() ==1 ?  1 : 0);
        paramMap.put("nameMd5", SecureUtil.md5(memberSourceInfo.getRealname()));
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("cityCode", Long.valueOf(memberSourceInfo.getCityCode()));
        paramMap.put("socialSecurity", XiaoLongQianBaoUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XiaoLongQianBaoUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XiaoLongQianBaoUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XiaoLongQianBaoUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XiaoLongQianBaoUtil.getBaoXian(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XiaoLongQianBaoUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XiaoLongQianBaoUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard", XiaoLongQianBaoUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XiaoLongQianBaoUtil.getXueLi(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XiaoLongQianBaoUtil.getShouru(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 2);
        paramMap.put("loanPurpose", XiaoLongQianBaoUtil.getYongTu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature", pushApiKeyParam.getApiCode());
        paramMap.put("huaBeiQuota", XiaoLongQianBaoUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("baiTiaoQuota", XiaoLongQianBaoUtil.getBaiTiao(memberSourceInfo.getBaitiao()));

        String encrypt = encrypt(pushApiKeyParam.getApiSecret(),JSON.toJSONString(paramMap));

        HashMap<String, Object> aceMap = new HashMap<>();
        String reqDate = String.valueOf(System.currentTimeMillis());
        String reqId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        aceMap.put("data",encrypt);
        aceMap.put("reqId",reqId);
        aceMap.put("reqDate",reqDate);

        log.info("【小龙钱包全流程】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【小龙钱包全流程】撞库结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        //Boolean check = data.getBoolean("check");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200") ) {
            JSONObject data = resultObject.getJSONObject("data");
            String name = data.getString("loanName");
            //Long productId = data.getLong("productId");
            String productName = data.getString("productName");
            String logo = data.getString("logo");

            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("orderNo",orderNo);
            infoObject.put("productId",orderNo);
            infoObject.put("productName",productName);
            infoObject.put("companyName",name);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("authorizationAgreement");
            for (int i=0;i<protocolList.size();i++){
                JSONObject jsonObject = new JSONObject();
                String protocolName = protocolList.getJSONObject(i).getString("name");
                String protocolUrl = protocolList.getJSONObject(i).getString("url");
                jsonObject.put("protocalName",protocolName);
                jsonObject.put("protocalUrl",protocolUrl);
                jsonArray.add(jsonObject);
            }
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if(ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                Double price = data.getDouble("price");
                BigDecimal priceNew = new BigDecimal(price);
                if(priceNew == null || priceNew.compareTo(new BigDecimal(0.00))== -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                //BigDecimal priceRight = typeRate.multiply(price);
                Double originPrice = data.getDouble("originPrice");
                BigDecimal priceRight = new BigDecimal(originPrice);
                pushApiResult.setPrice(priceRight);
                pushApiResult.setPriceRight(priceNew);
            }
            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }
        }

        return pushApiResult;
    }

    public static String encrypt(String key, String str) {
        try {

            byte[] raw = key.getBytes(StandardCharsets.UTF_8);

            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encrypted =cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));

            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {

            log.error("AES 加密异常", e);

            throw new RuntimeException(e);

        }
    }


    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("sex", memberSourceInfo.getSex() ==1 ?  1 : 0);
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("cityCode", Long.valueOf(memberSourceInfo.getCityCode()));
        paramMap.put("socialSecurity", XiaoLongQianBaoUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("accumulationFund", XiaoLongQianBaoUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("carProduction", XiaoLongQianBaoUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("estate", XiaoLongQianBaoUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("unitSocialSecurity", XiaoLongQianBaoUtil.getBaoXian(memberSourceInfo.getBaoxian()));
        paramMap.put("sesame", XiaoLongQianBaoUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("professionalIdentity", XiaoLongQianBaoUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("customerCreditCard", XiaoLongQianBaoUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        paramMap.put("highestEducation", XiaoLongQianBaoUtil.getXueLi(memberSourceInfo.getXueli()));
        paramMap.put("monthlyIncome", XiaoLongQianBaoUtil.getShouru(memberSourceInfo.getShouru()));
        paramMap.put("customerFormOfPayroll", 1);
        paramMap.put("lengthOfService", 2);
        paramMap.put("loanPurpose", XiaoLongQianBaoUtil.getYongTu(memberSourceInfo.getYongtu()));
        paramMap.put("channelSignature", pushApiKeyParam.getApiCode());
        paramMap.put("huaBeiQuota", XiaoLongQianBaoUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("baiTiaoQuota", XiaoLongQianBaoUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        String encrypt = encrypt(pushApiKeyParam.getApiSecret(),JSON.toJSONString(paramMap));

        HashMap<String, Object> aceMap = new HashMap<>();
        String reqDate = String.valueOf(System.currentTimeMillis());
        String reqId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        aceMap.put("data",encrypt);
        aceMap.put("reqId",reqId);
        aceMap.put("reqDate",reqDate);

        log.info("【小龙钱包全流程】导单开始【requestUrl】{}【paramMap】{}【aceMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【小龙钱包全流程】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (code == 200){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (code == 200) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;

    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "success");
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }


}
